<?php
class sms_controller_system extends sms_controller_index{
	public function __construct($app, $controller){
		parent::__construct($app, $controller);
		$this->notice = new sms_model_system();
	}
	
	public function mytest_action(){
		$this->requireLogin();
		$uid = self::$login['uid'];
		$params = array(
				'senderid'		=> 5164303,
				'reciverid'	=> 4892787,
				'type'	=> '[:friends|bind:]'
			);
		$senderid = 5164303;
		$reciverid = 4892787;
		$type = '[:friends|add:]';
		$ret =sms_util_system::upSmsStatus($senderid,$reciverid,$type);
		//$args = array('thread_id'=>'','uid'=>'','app'=>'','control'=>'','act'=>'','rid'=>'','authorid'=>''
//		$ret = $this->sms->updateSmsCount($uid,sms_config::MSG_DKP_CNT,1);
		var_dump($ret);exit;
//		$res = sms_util_system::send('fza','5164303','你与<a href="/?uid=4892787">bigbear1113</a>成为好友。','[:friends|bind:]',serialize(array('id'=>5164303)),time());
//		var_dump($res);
		/*if ($res) {
			$id = $this->notice->addRel(array(
						'sms_id'=>$res,
						'reciever_id'=>5164303,
						'reciever'=>fza,
						'readed'=>0
					));
			var_dump($id);
		}*/
	}
	
	public function view_inbox_action(){
		$this->requireLogin();
		$this->headerView = $this->rootDir."/views/index/_header.phtml";
		$uid = self::$login['uid'];
		$page = _('page', 1);
		$type = _('type',0);
		$ret = CacheManager::getInstance()->get(array(
			'app'=>$this->app,
			'func'=>array(
				array($this->notice, 'selectSysInboxPage'), 
				array($uid, $page, sms_model_data::PAGE_SIZE,$type)				
			)
		));
//		$ret = $this->notice->selectSysInboxPage($uid,$page,sms_model_data::PAGE_SIZE,$type);
		sms_util_text::formatSystemRows($ret['ROWS']);
		$pages = $this->genPages($ret['INFO']);
		$this->type = $type;
		$this->ret = self::success(array('ret'=>$ret, 'pages'=>$pages));
		$this->view = 'inbox';
//		$this->headerView = $this->viewDir."/_header.phtml";
	}
	
//	public function view_readsys_action(){
//		$this->requireLogin();
//		$uid = self::$login['uid'];
//		$sms_id = _('sms_id', 0);
//		$sms = $this->sms->select($sms_id);
//		if(!$sms){
//			$this->ret = self::failure(Error::ERROR_RECORD_NOT_FOUND , array('记录不存在'));
//			return;
//		}
//		$recievers = $this->sms_reciever->select($sms_id);
//		$recievers2 = array();
//		$exists = false;
//		foreach($recievers as $i=>&$reciever){
//			if($reciever['uid']==$uid) {
//				$exists = true;
//			}
//			array_push($recievers2, "<a href='/?uid=".$reciever['uid']."'>".$reciever['username']."</a>");
//			
//		}
//		
//		if(!$exists){
//			$this->ret = self::failure(Error::ERROR_WRONG_OWNER);
//			return;
//		}
//		$messages = $this->sms_message->select($sms_id);
//		$this->ret = self::success(array('sms'=>$sms, 'recievers'=>$recievers2, 'messages'=>$messages));
//		$this->view = 'sys_read';
//		
//	}

	
	public function send_action(){
//		Log::getInstance()->log('####################################******************', LOG_INFO);
		$this->_renderJson();
		$reciever = _('reciever');
		$reciever_id = _('reciever_id');
		$title = _('title');
		$content = _('content');
		$sender_name = _('sender_name', '[:system:]');
		$target = _('target', "");
		$time = _('time');
		$checksum = _('checksum');
//		$encoding=_('encoding', 'utf-8');
		$uid = _('senderid',0);
		$username = $sender_name;
		$type = 0;
//		Log::getInstance()->log(sms_util_verifier::systemChecksum($reciever, $reciever_id, $title, $content, $sender_name, $target, $time).'='.$checksum, LOG_INFO);
		if(!sms_util_verifier::checkLink($reciever, $reciever_id, $title, $content, $sender_name, $target, $time, $checksum)){
			$this->ret = self::failure(Error::ERROR_CHECKSUM );
			return; // 数据不符
		}
		
		if(abs($time - time())>300){
			$this->ret = self::failure(Error::ERROR_EXPIRE );
			return ; // 数据超时
		}	
		$recievers = explode(",", $reciever);
		$reciever_ids = explode(",", $reciever_id);
		trim_params($recievers);
		trim_params($reciever_ids);
		$arr_failed_user = array();
		$arr_recieverid = array();
		if($reciever_ids){
			$i=0;
			foreach ($reciever_ids as $v){
				$reciever_name = $recievers[$i];
				if (!$reciever_name) {
					$userInfo = friends_util_cache::getUserInfo($v);
					$reciever_name = $userInfo['username'];
				}
				$sms_id = $this->notice->add(
							array(
								'senderid' => $uid,
								'sender' => $username,
								'title' => $title,
								'recieverid' => $v,
								'reciever' => $reciever_name,
								'content' => $content,
								'target' =>$target
							)
						);
				if (!$sms_id) {
					$this->ret = self::failure(Error::ERROR_UNKNOWN );
					array_push($arr_failed_user,$v);
				}else
					array_push($arr_recieverid,$v);
				++$i;
			}
			if($arr_failed_user){
				$this->ret = self::failure(Error::ERROR_UNKNOWN );
				return; // 数据库错误
			}else {
				$this->ret = array('result'=>true);
			}
			foreach($reciever_ids as $uid){
				CacheManager::getInstance()->refresh($this->app, '',$uid);
			}
		}
		else {
			$this->ret = self::failure(self::ERROR_NO_RECIEVER );
			return ;
		}
		/*$r = array('uid'=>0, 'username'=>'');
		$count = 0;
		if(trim($reciever)!='' and count($recievers)>=count($reciever_ids)){
			$use_name = true;
		}else{
			$use_name = false;
			$recievers = $reciever_ids;
		}
		foreach($recievers as $i=>$reciever){
			try{
				if($use_name){
					$user = Cache::cacheFunction(array($this->SL, 'soap_query_user_by_username'), array($reciever));
					array_push($reciever_ids, $user['acc_id']);
				}
				else{ 
					$user = Cache::cacheFunction(array($this->SL, 'soap_query_user'), array($reciever));
				}
			}catch (Exception $e){
				$user = false;
			}
			if($user){
				if($i==0){
					$r['uid'] = $user['acc_id'];
					$r['username'] = $user['acc_nickname'];
				}
				$flag = $this->notice->addRel(
					array(
						'sms_id'=>$sms_id,
						'reciever_id'=>$user['acc_id'],
						'reciever'=>$user['acc_nickname'],
						'readed'=>($user['acc_id']==$uid?0:1),
						'sender' => $username
					)
				);
				if($flag) $count ++;
			}
		}*/
		/*if($count<1){
			$this->ret = self::failure(self::ERROR_NO_RECIEVER );
			$this->notice->rollback($sms_id,true);
			return; // 收件人填写错误
		}*//*		
		$flag = $this->sms_message->add(
			array('sms_id'=>$sms_id, 'sender_id'=>$uid, 'sender_name'=>$username,
			'reciever_id'=>$r['uid'], 'reciever_name'=>$r['username'],
			'content'=>$content, 'type'=>$type )
		);
		if(!$flag){
			$this->ret = self::failure(Error::ERROR_UNKNOWN ); // 数据库错误
			$this->rollback($sms_id);
		}*//*else{
			$this->ret = array('result'=>true);
		}*/
		
	}
	
	/**
	 * 发用户警告
	 * Enter description here ...
	 */
	public function sendWarnig_action(){
		$this->_renderJson();
		$uid 		= 	_('uid');	//要发的对象
		$type		= 	_('type');	//发警告的类型：日志 1 相册 2 转贴 3
		$checksum	=	_('code');	//验证码
		if(!is_numeric($uid) || !is_numeric($type) || sms_util_system::getVerifyCode(array($uid,$type),VERIFY_CODE)!==$checksum) $this->ret = self::failure(Error::ERROR_DATA ); // 验证失败
		$userInfo = friends_util_cache::getUserInfo($uid);
		$reciever_name = $userInfo['username'];
		$data = array(
					'senderid' => 0,
					'sender' => '[:nga:]',
					'recieverid' => $uid,
					'reciever' => $reciever_name,
					'content' => $_SERVER['config']['warn'][$type]['msg'],
					'target' =>1
					);
		if($sms_id = $this->notice->add($data)){
			$this->ret = self::success($sms_id);
			
		} else		
			$this->ret = self::failure(Error::ERROR_UNKNOWN ); // 数据库错误	
		return;
	}
	
	
	public function send_old_action(){
//		Log::getInstance()->log('####################################******************', LOG_INFO);
		$this->_renderJson();
		$reciever = _('reciever');
		$reciever_id = _('reciever_id');
		$title = _('title');
		$content = _('content');
		$sender_name = _('sender_name', '[:system:]');
		$target = _('target', "");
		$time = _('time');
		$checksum = _('checksum');
//		$encoding=_('encoding', 'utf-8');
		$uid = 0;
		$username = $sender_name;
		$type = 0;
//		Log::getInstance()->log(sms_util_verifier::systemChecksum($reciever, $reciever_id, $title, $content, $sender_name, $target, $time).'='.$checksum, LOG_INFO);
		if(!sms_util_verifier::checkLink($reciever, $reciever_id, $title, $content, $sender_name, $target, $time, $checksum)){
			$this->ret = self::failure(Error::ERROR_CHECKSUM );
			return; // 数据不符
		}
		
		if(abs($time - time())>300){
			$this->ret = self::failure(Error::ERROR_EXPIRE );
			return ; // 数据超时
		}
		
//		if(strtoupper($encoding) != 'UTF-8'){
//			$reciever = iconv('GB18030', 'UTF-8', $reciever);
//			$title = iconv('GB18030', 'UTF-8', $title);
//			$content = iconv('GB18030', 'UTF-8', $content);
//		}		
		$recievers = explode(",", $reciever);
		$reciever_ids = explode(",", $reciever_id);
		trim_params($recievers);
		trim_params($reciever_ids);
		if(!$recievers[0]){
			$firstreciever=Cache::cacheFunction(array($this->SL, 'soap_query_user_by_username'), array($reciever_ids[0]));
			$firstreciever = $firstreciever['acc_nickname'];
		}else $firstreciever = $recievers[0];
		$sms_id = $this->notice->add(
			array(
				'senderid' => $uid,
				'sender' => $username,
				'recieverid' => $reciever_ids[0],
				'reciever' => $firstreciever,
				'content' => $content,
				'target' =>$target
			)
			);
		if(!$sms_id){
			$this->ret = self::failure(Error::ERROR_UNKNOWN );
			return; // 数据库错误
		}
		$r = array('uid'=>0, 'username'=>'');
		$count = 0;
		if(trim($reciever)!='' and count($recievers)>=count($reciever_ids)){
			$use_name = true;
		}else{
			$use_name = false;
			$recievers = $reciever_ids;
		}
		foreach($recievers as $i=>$reciever){
			try{
				if($use_name){
					$user = Cache::cacheFunction(array($this->SL, 'soap_query_user_by_username'), array($reciever));
					array_push($reciever_ids, $user['acc_id']);
				}
				else{ 
					$user = Cache::cacheFunction(array($this->SL, 'soap_query_user'), array($reciever));
				}
			}catch (Exception $e){
				$user = false;
			}
			if($user){
				if($i==0){
					$r['uid'] = $user['acc_id'];
					$r['username'] = $user['acc_nickname'];
				}
				$flag = $this->notice->addRel(
					array(
						'sms_id'=>$sms_id,
						'reciever_id'=>$user['acc_id'],
						'reciever'=>$user['acc_nickname'],
						'readed'=>($user['acc_id']==$uid?0:1),
						'sender' => $username
					)
				);
				if($flag) $count ++;
			}
		}
		if($count<1){
			$this->ret = self::failure(self::ERROR_NO_RECIEVER );
			$this->notice->rollback($sms_id,true);
			return; // 收件人填写错误
		}/*		
		$flag = $this->sms_message->add(
			array('sms_id'=>$sms_id, 'sender_id'=>$uid, 'sender_name'=>$username,
			'reciever_id'=>$r['uid'], 'reciever_name'=>$r['username'],
			'content'=>$content, 'type'=>$type )
		);
		if(!$flag){
			$this->ret = self::failure(Error::ERROR_UNKNOWN ); // 数据库错误
			$this->rollback($sms_id);
		}*/else{
			$this->ret = array('result'=>true);
		}
		
		foreach($reciever_ids as $uid){
			CacheManager::getInstance()->refresh($this->app, '',$uid);
		}
		
	}
	
	function remove_action(){
		$this->_renderJson();
		if(!self::$login){
			$this->ret = self::failure(Error::ERROR_NOT_LOGIN );
		}else{
			$uid = self::$login['uid'];
			$id = $this->id;
			$isAll = _('all',0);
			if($isAll==1){
				$id = '';
			}
			elseif(false!==strpos($id,'|')){
				$id = explode('|',$id);
			}
			$type = _('type',0);
			$flag = $this->notice->deleteSystem($uid,$id,$type);
			if($flag){
				$this->ret = self::success();
				if($isAll==1){
					$this->addMessage('清空收件箱成功！');
				}
				CacheManager::getInstance()->refresh($this->app);
			}else{
				$this->ret = self::failure(Error::ERROR_UNKNOWN );
			}
		}
	}
	
	function update_status_action(){
		$this->_renderJson();
		if(!self::$login){
			$this->ret = self::failure(Error::ERROR_NOT_LOGIN );
			return;
		}
		if($id = _('id', 0))
			$row = $this->notice->select($id);
		elseif(_('senderid') && _('reciverid') && _('type')){
			$row = $this->notice->getSysNoticeByUid(_('senderid'),_('reciverid'),_('type'));
		}
		if(!$row){
			$this->ret = self::failure(Error::ERROR_RECORD_NOT_FOUND );
			return;
		}
		$target = unserialize($row['target']);
		if(!$target){
			$this->ret = self::failure(Error::ERROR_DATA);
			return;
		}
		if($target['id'] != $id){
			$this->ret = self::failure(Error::ERROR_DATA );
			return;
		}
		$sender_name = sms_util_text::parseSenderName($row['username']);
//		var_dump($sender_name);
		$type = $this->type?$this->type:$target['type'];
		if(key_exists($type, $_SERVER['LOCALE']['apps'][$sender_name][1]['return'])){
			$target['return'] = eval_template($_SERVER['LOCALE']['apps'][$sender_name][1]['return'][$type], $target);
		}else{
			$target['return'] = eval_template($_SERVER['LOCALE']['apps'][$sender_name][1]['return'][$target['type']], $target);
		}
		$this->notice->updateTarget($id, $target);
		
		$this->ret = self::success($target['return']);
		CacheManager::getInstance()->refresh($this->app);
	}
	
	function refuseCiteNotice_action(){
		$this->_renderJson();
		$uid = self::$login['uid'];
		if($this->notice->refuseCiteNotice($uid)){
			$this->ret = self::success(true);
		}else {
			$this->ret = self::failure(Error::ERROR_DATA);
		}
		return ;
	}
}